<template>
  <div>
    <a-table
      :pagination="false"
      :columns="sceneColumns"
      :data-source="sceneData"
      bordered
      row-key="id"
      class="scene-table"
    >
      <!-- <span slot="index" slot-scope="text, record, index">{{ index + 1 }}</span> -->
      <template
        slot="628129025809846273"
        slot-scope="text, record, index"
      >
        <BaseInput />
      </template>
    </a-table>
    <a-table
      :show-header="false"
      :pagination="false"
      :columns="businessColumns"
      :data-source="businessData"
      bordered
      row-key="id"
      class="business-table"
    >
      <span
        slot="index"
        slot-scope="text, record, index"
      >{{ index + 1 }}</span>
      <template
        v-for="col in ['dd']"
        :slot="col"
        slot-scope="text, record, index"
      >
        <div :key="col">
          <!-- <template v-if="record.editable">
                        <BaseInput :value="text" :disabled="col === 'amount'"
                                @blur="e => handleChange(e.target.value, record.id, col)"/></template> -->
          <template v-if="index === 0">
            {{ record.tableName }}
          </template>
          <template v-else>
            {{ text }}
          </template>
        </div>
      </template>
    </a-table>
    <a-table
      :show-header="false"
      :pagination="false"
      :columns="projectColumns"
      :data-source="projectData"
      bordered
      row-key="id"
      class="project-table"
    >
      <span
        slot="index"
        slot-scope="text, record, index"
      >{{ index + 1 }}</span>
      <template
        v-for="col in ['dd']"
        :slot="col"
        slot-scope="text, record, index"
      >
        <div :key="col">
          <!-- <template v-if="record.editable">
                        <BaseInput :value="text" :disabled="col === 'amount'"
                                @blur="e => handleChange(e.target.value, record.id, col)"/></template> -->
          <template v-if="index === 0">
            {{ record.tableName }}
          </template>
          <template v-else>
            {{ text }}
          </template>
        </div>
      </template>
    </a-table>
    <a-table
      v-if="scoreTableLength === 4"
      :show-header="false"
      :pagination="false"
      :columns="totalColumns"
      :data-source="totalData"
      bordered
      row-key="id"
      class="total-table"
    >
      <span
        slot="index"
        slot-scope="text, record, index"
      >{{ index + 1 }}</span>
      <template
        v-for="col in ['dd']"
        :slot="col"
        slot-scope="text, record, index"
      >
        <div :key="col">
          <template v-if="record.editable">
            <BaseInput
              :value="text"
              :disabled="col === 'amount'"
              @blur="e => handleChange(e.target.value, record.id, col)"
            />
          </template>
          <template v-else>
            {{ text }}
          </template>
        </div>
      </template>
    </a-table>
    <!-- <material-list ref="detailDialog" @createList="createList"></material-list> -->
  </div>
</template>
<script>
import { recordDetailAdd, recordView, editScore } from '@/api/material/check/record'
import { columns } from './insideModel'
import cloneDeep from 'lodash.clonedeep' // 深拷贝
const data = []
const renderContent = (value, row, index) => {
    const obj = {
        children: value,
        attrs: {}
    }
    if (index === 0) {
        obj.attrs.colSpan = 0
    }
    return obj
}
export default {
	name:'a'+Date.now(),
    props: {
        state: {
            type: [Number, String]
        },
        row: {
            type: Object
        },
        disabled: {
            type: Boolean,
            default: false
        }
    },
    data() {
        this.cacheData = data.map(item => ({ ...item }))
        return {
            haveScore: false,
            sceneColumns: [],
            businessColumns: [],
            projectColumns: [],
            totalColumns: [],
            businessData: [],
            projectData: [],
            totalData: [],
            sceneData: [],
            selectedId: [],
            sendHeader: [],
            sendTable: [],
            scoreTableLength: -1//评分表长度，3个的话，提交的时候，总计的数据会为空，所以这里把长度留下来判断一下
        }
    },
    mounted: function() {
        this.list()
    },
    methods: {
        initTable() {
            this.pageNo = 1
        },
        async list() {
            let res
            let params = null

            if (this.row.haveScore || this.haveScore) {
                // if (true) {
                params = { id: this.row.id, detailType: this.row.checkPlaceStr }
                res = await recordView(params)
            } else {
                params = { baseId: this.row.id, detailType: this.row.checkPlaceStr }
                res = await recordDetailAdd(params)
            }
            // this.$console(re/s)
            console.log(res)

            // resultRequest(params).then(res => {
            if (res.code === 200) {
                let arr = res.data.sixMeasuresScoringVos
                this.scoreTableLength = arr.length
                this.sceneData = arr[0].content
                this.sceneHeader = arr[0].header // 存储header数据，不需要在data中声明

                // 计算标准分列的总分
                const standScoreDataIndex = this.getDataIndex(this.sceneHeader, '3')
                const sum = this.sceneData.reduce((pre, cur) => {
                    const num = Number(cur[standScoreDataIndex])
                    if(!isNaN(num)) {
                        return pre + num
                    }
                    return pre
                }, 0)

                const map = {
                    renderValue: true, // 只渲染value，不用渲染input框
                    id: 'fakerow' + (new Date()).getTime()
                }
                this.sceneHeader.forEach(column => {
                    if(column.code === '2') { // 检查内容列
                        map[column.dataIndex] = '小计'
                        return
                    }
                    if(column.code === '3') { // 标准分列
                        map[column.dataIndex] = sum
                        return
                    }
                    map[column.dataIndex] = ''
                })
                this.sceneData.push(map)

                this.sceneColumns = this.customHeaderRender(arr[0].header, this.sceneData, 0)
                this.businessData = arr[1].content
                this.businessHeader = arr[1].header
                this.businessColumns = this.customHeaderRender(arr[1].header, this.businessData, 1)
                this.projectData = arr[2].content
                this.projectHeader = arr[2].header
                this.projectColumns = this.customHeaderRender(arr[2].header, this.projectData, 2, true)
                if (this.scoreTableLength === 4) {
                    this.totalData = arr[3].content
                    this.totalColumns = this.customHeaderRender(arr[3].header, this.totalData, 3)
                }
                // 初始化合计值
                this.notifyChangeAllTotal()
            }
            // })
        },
        /**
         * 通知每个表格，合计需要重新计算
         */
        notifyChangeAllTotal() {
            const calcTotal = (list, header) => {
                // 检查项的dataIndex
                const examDataIndex = this.getDataIndex(header, '1')
                // 小计项的dataIndex
                const subTotalIndex = this.getDataIndex(header, '6')
                const map = {}
                let total = 0
                list.forEach(item => {
                    if(item.id?.indexOf('fakerow') > -1) return // 不统计小计那一行（前端造的数据）
                    const curNum = Number.isFinite(Number(item[subTotalIndex])) ? Number(item[subTotalIndex]) : 0
                    // 同一检查项的小计值只累加一次，用map做标记
                    if(!map[item[examDataIndex]]) {
                        total += curNum
                        map[item[examDataIndex]] = true
                    }
                })
                return total
            }
            const sceneDataTotal = calcTotal(this.sceneData, this.sceneHeader)
            const finalItem = this.sceneData[this.sceneData.length - 1]
            if(finalItem.id?.indexOf('fakerow') > -1) { // 前端造的数据
                const subTotalIndex = this.getDataIndex(this.sceneHeader, '6') // 小计列
                finalItem[subTotalIndex] = sceneDataTotal
            }
            const businessDataTotal = calcTotal(this.businessData, this.businessHeader)
            // (现场检查得分*90%）+（业务考核得分*10%）
            const allTotal = (sceneDataTotal * 90 + businessDataTotal * 10) / 100
            this.projectData.forEach(item => {
                this.$set(item, 'totalNum', allTotal)
            })
        },
        /**
         * 自定义列渲染
         * @param {Array} headerArr 表头
         * @param {Array} data 表内容
         * @param {Number} tableIndex 表序号
         * @param {Boolean} showTotal 是否显示合计值
         */
        customHeaderRender(headerArr, data, tableIndex, showTotal = false) {
            let result = []
            const self = this
            headerArr.map((item) => {
                if (item.code === '1' || item.code === '5' || item.code === '6') {
                    const checkResultDataIndex = this.getDataIndex(headerArr, '5') // 检查结果记录的dataIndex
                    item.customRender = function(value, row, index) {
                        const obj = {
                            children: row.renderValue ? value : !index ?
                                <div class="record-table-name">{row.tableName}</div> : item.code === '5' && !self.disabled ?
                                    <input class="result-change" value={row[checkResultDataIndex]} onInput={(e) => {
                                        row[checkResultDataIndex] = e.target.value
                                    }} disabled={self.state == 3} /> : value,
                            attrs: {}
                        }
                        // 若该行考核内容和上一行一致，则使其隐藏
                        if (index !== 0 && data[index - 1][headerArr[0].dataIndex] === row[headerArr[0].dataIndex]) {
                            obj.attrs.rowSpan = 0
                            // 若不是，则往下合并与改行考核内容一致行的总行数
                        } else {
                            obj.attrs.rowSpan = cloneDeep(data).filter((i) => i[headerArr[0].dataIndex] === row[headerArr[0].dataIndex]).length
                        }
                        if (index === 0 && item.code === '1') {
                            obj.attrs.colSpan = showTotal ? 5 : 6
                        }
                        if (index === 0 && item.code === '5') {
                            obj.attrs.colSpan = 0
                            item.width = '20%'
                        }
                        if (index === 0 && item.code === '6') {
                            obj.attrs.colSpan = showTotal ? 1 : 0
                            item.width = '20%'
                            obj.children = row.totalNum
                        }
                        return obj
                    }
                    item.width = '10%'
                }
                if (item.code === '2') {
                    item.width = '30%'
                    item.customRender = renderContent
                }
                if (item.code === '3') {
                    item.width = '10%'
                    item.customRender = renderContent
                }
                if (item.code === '4') {
                    item.width = '10%'
                    item.customRender = (value, row, index) => {
                        const standDataIndex = this.getDataIndex(headerArr, '3') // 标准分的dataIndex
                        const dataIndex = this.getDataIndex(headerArr, item.code) // 实得分的dataIndex
                        const examDataIndex = this.getDataIndex(headerArr, '1') // 检查项的dataIndex
                        const subTotalIndex = this.getDataIndex(headerArr, '6') // 小计项的dataIndex
                        const obj = {
                            children: row.renderValue ? value : index > 0 && !self.disabled ? <input class="score-change" value={row[dataIndex]} onInput={(e) => {
                                const val = e.target.value
                                row[dataIndex] = val
                            }} onBlur={(e) => {
                                const val = e.target.value
                                let errFlag = false
                                if (!errFlag && !Number.isFinite(Number(val))) {
                                    this.$message.error('实得分必须为数字')
                                    row[dataIndex] = ''
                                    errFlag = true
                                }
                                if (!errFlag && Number(val) > Number(row[standDataIndex])) {
                                    this.$message.error('实得分不能大于标准分')
                                    row[dataIndex] = ''
                                    errFlag = true
                                }
                                // 计算小计值
                                const sum = data.reduce((pre, cur) => {
                                    const flag = cur[examDataIndex] === row[examDataIndex] // 如果是同一检查项，则计算和
                                    const curNum = Number.isFinite(Number(cur[dataIndex])) && flag ? Number(cur[dataIndex]) : 0
                                    return pre + curNum
                                }, 0)
                                data.forEach(item => {
                                    const flag = item[examDataIndex] === row[examDataIndex] // 给同一检查项的数据行的小计赋值
                                    flag && this.$set(item, subTotalIndex, sum)
                                })
                                // 计算合计值
                                this.notifyChangeAllTotal()
                            }}  disabled={this.state == 3} /> : value,
                            attrs: {}
                        }
                        if (index === 0) {
                            obj.attrs.colSpan = 0
                        }
                        return obj
                    }
                }
                result.push(item)
            })
            return result
        },
        getDataIndex(columnList, code) {
            return columnList.find(item => item.code === code).dataIndex
        },
        getResult: function(columns, data, num, value, key) {
            let params = {}
            this.sendHeader = JSON.parse(JSON.stringify(columns))
            this.sendTable = JSON.parse(JSON.stringify(data))
            for (let i = 0; i < this.sendTable.length; i++) {
                if (this.sendTable[i].id === key) {
                    this.sendTable[i][columns[num].dataIndex] = value
                    break
                }
            }
            params['content'] = this.sendTable.slice(1, this.sendTable.length)
            params['header'] = this.sendHeader
            return params
        },
        submit: function() {
            return new Promise((resolve, reject) => {
                let params = {
                    siteFormDto: {
                        // 筛选掉前端造的那一列，否则接口会报错
                        content: this.sceneData.slice(1, this.sceneData.length).filter(item => item?.id?.indexOf('fakerow') < 0),
                        header: this.sceneColumns
                    },
                    businessFormDto: {
                        content: this.businessData.slice(1, this.businessData.length),
                        header: this.businessColumns
                    },
                    inspectionFormDto: {
                        content: this.projectData.slice(1, this.projectData.length),
                        header: this.projectColumns
                    }
                }
                //评分表长度为3个的话，总计的数据的获取位置一相同
                if (this.scoreTableLength === 3) {
                    params.attachmentFormDto = {
                        content: this.projectData.slice(1, this.projectData.length),
                        header: this.projectColumns
                    }
                } else {
                    params.attachmentFormDto = {
                        content: this.totalData.slice(1, this.totalData.length),
                        header: this.totalColumns
                    }
                }
                let result = Object.assign({ baseId: this.row.id }, params, this.queryParam)
                editScore(result).then(res => {
                    if (res.code === 200) {
                        this.$message.success('暂存成功')
                        this.haveScore = true
                        resolve()
                    } else {
                        reject()
                    }
                }).catch(() => {
                    reject()
                })
            })
        }
    }
}
</script>
